﻿/*
 * Created by SharpDevelop.
 * User: 1987wing
 * Date: 2015/4/11
 * Time: wing 23:32
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Net;
using System.IO;

namespace Update.Core
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		private string downloadURL;
    	private string savePath;
		
		public MainForm(string downloadURL, string savePath)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
			this.downloadURL = downloadURL;
            this.savePath = savePath;
		}
		
		public MainForm() {
			InitializeComponent();
			
			//this.downloadURL = @"ftp://172.16.125.38/CtripSOA.exe";
			this.downloadURL = @"ftp://172.16.125.38/ico/10004.ico";
			this.savePath = @"E:\CtripSOA.exe";
		}
		
		private void progressBar1_Click(object sender, EventArgs e)
        {
			
        }
		  
		private void Form1_Load(object sender, EventArgs e)
        {
            //DownloadFile(this.downloadURL, this.savePath, progressBar1, label1);
            this.DownloadFileFromServer(new Uri(this.downloadURL), this.savePath);
        }
		
		public bool DownloadFileFromServer(Uri serverUri, string localFileName)
		{
		    // The serverUri parameter should start with the ftp:// scheme.
		    if (serverUri.Scheme != Uri.UriSchemeFtp)
		    {
		        return false;
		    }
		    // Get the object used to communicate with the server.
		    // Note that the cast to FtpWebRequest is done only
		    // for the purposes of illustration. If your application
		    // does not set any properties other than those defined in the
		    // System.Net.WebRequest class, you can use the following line instead:
		    // WebRequest request = WebRequest.Create(serverUri);
		    //
		    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
		    request.Method = WebRequestMethods.Ftp.DownloadFile;
		    
		    FtpWebResponse response = (FtpWebResponse) request.GetResponse();
		    
		    Stream responseStream = null;
		    StreamReader readStream = null;
		    StreamWriter writeStream = null;
		    try
		    {
		        responseStream = response.GetResponseStream(); 
		        readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
		        // Display information about the data received from the server.
		        Console.WriteLine("Bytes received: {0}",response.ContentLength);   
		         
		        Console.WriteLine("Message from server: {0}", response.StatusDescription);
		        Console.WriteLine("Resource: {0}", response.ResponseUri);
		       
		        // Write the bytes received from the server to the local file.
		        if (readStream != null)
		        {
		            writeStream = new StreamWriter(localFileName, false);
		            writeStream.Write(readStream.ReadToEnd());
		        }
		    }
		    finally
		    {
		        if (readStream != null)
		        {
		            readStream.Close();
		        }
		        if (response != null)
		        {
		            response.Close();
		        }
		        if (writeStream != null)
		        {
		            writeStream.Close();
		        }
		    }
		    return true;
		}
		
		public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;
            try
            {
            	Uri uri = new Uri(URL);
                FtpWebRequest Myrq = (FtpWebRequest)WebRequest.Create(uri);
                Myrq.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse myrp = (System.Net.FtpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                long downloadBytes = 0;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    downloadBytes = osize + downloadBytes;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalBytes;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)downloadBytes / (float)totalBytes * 100;
                    label1.Text = "下载进度：" + percent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                
                if (percent == 100) {
                	this.beginInstall.Text = "完成";
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception e)
            {
            	MessageBox.Show(e.ToString());
            }
        }
		
		private void BeginInstallClick(object sender, EventArgs e)
		{
			Process.Start(@"E:\CtripSOA源文件\WindowsFormsApplication1\bin\Debug\CtripSOA.exe");
            
            ExeCommand("taskkill /im Update.Core.exe /f ");
		}
		
		 //执行命令
        private void ExeCommand(string commandText)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            try
            {
                p.Start();
                p.StandardInput.WriteLine(commandText);
                p.StandardInput.WriteLine("exit");
                //p.StandardOutput.ReadToEnd();
            }
            catch (Exception e)
            {
            	MessageBox.Show(e.ToString());
            }
        }
	}
}
